package com.cpr.ams.web.controller;


import com.cpr.ams.bean.BasePrivilege;
import com.cpr.ams.bean.BaseUser;
import com.cpr.ams.bean.BaseUserExample;
import com.cpr.ams.bean.extend.BaseUserExtend;
import com.cpr.ams.bean.extend.Statistical;
import com.cpr.ams.exception.AmsException;
import com.cpr.ams.service.IBasePrivilegeService;
import com.cpr.ams.service.IBaseUserService;
import com.cpr.ams.util.ExcelUtils;
import com.cpr.ams.util.Result;
import com.cpr.ams.util.StatusCode;
import com.cpr.ams.vm.UserRoleVM;
import com.sun.istack.internal.NotNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @description: 用户基础控制器类
 * @author: GX Cui
 * @Date 11:34 下午 2021/4/11
 */
@Api(value = "用户管理",tags = {"用户管理接口"})
@Validated
@RestController
@RequestMapping("/baseUser")
public class BaseUserController {
    @Autowired
    private IBaseUserService baseUserService;
    @Autowired
    private IBasePrivilegeService basePrivilegeService;

    @ApiOperation(value = "查询不同角色的用户")
    @GetMapping("findUsersByRoleId/{roleId}")
    public Result findUsersByRoleId(@PathVariable int roleId){
        List<BaseUser> list = baseUserService.findByRoleId(roleId);
        return Result.success(list);
    }

    @ApiOperation(value = "通过ID查询权限信息")
    @GetMapping("findMenuByUserId/{id}")
    public Result findMenuByUserId(@PathVariable int id){
        List<BasePrivilege> list =  basePrivilegeService.findMenuByUserId(id);
        return Result.success(list);
    }

    @ApiOperation(value = "查询所有")
    @GetMapping(value = "findAll")
    public Result findAll(){
        List<BaseUser> list = baseUserService.findAll();
        return Result.success(list);
    }

    @ApiOperation(value = "级联查询所有",notes = "级联用户角色")
    @GetMapping(value = "cascadeRoleFindAll")
    public Result cascadeRoleFindAll(){
        List<BaseUserExtend> list = baseUserService.cascadeRoleFindAll();
        return Result.success(list);
    }

    @ApiOperation(value = "保存或更新")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "主键",dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "idCard",value = "身份证号",paramType = "query",required = false),
            @ApiImplicitParam(name = "userName",value = "用户姓名",paramType = "query",required = true),
            @ApiImplicitParam(name = "gender",value = "性别",paramType = "query",required = false),
            @ApiImplicitParam(name = "phoneNumber",value = "手机号",paramType = "query",required = true),
            @ApiImplicitParam(name = "healthCode",value = "健康码状态",paramType = "query",required = false),
            @ApiImplicitParam(name = "password",value = "密码",paramType = "query",required = false),
            @ApiImplicitParam(name = "registerTime",value = "注册时间",paramType = "query",required = false),
            @ApiImplicitParam(name = "userFace",value = "头像",paramType = "query",required = false),
            @ApiImplicitParam(name = "status",value = "账号状态",paramType = "query",required = false),
            @ApiImplicitParam(name = "backup1",value = "备用字段1",paramType = "query",required = false),
            @ApiImplicitParam(name = "backup2",value = "备用字段2",paramType = "query",required = false)
    })
    @PostMapping(value = "saveOrUpdate")
    public Result saveOrUpdate(Integer id,
                               String idCard,
                               @NotNull String userName,
                               String gender,
                               @NotNull String phoneNumber,
                               Integer healthCode,
                               String password,
                               String userFace,
                               String backup1,
                               String backup2){
        BaseUser baseUser = new BaseUser();
        baseUser.setId(id);
        baseUser.setIdCard(idCard);
        baseUser.setUserName(userName);
        baseUser.setGender(gender);
        baseUser.setPhoneNumber(phoneNumber);
        baseUser.setHealthCode(healthCode);
        baseUser.setPassword(password);
        baseUser.setUserFace(userFace);
        baseUser.setBackup1(backup1);
        baseUser.setBackup2(backup2);
        try{
            int i = baseUserService.saveOrUpdate(baseUser);
            return Result.success(i);

        }catch (AmsException ams){
            if(ams.getStatusCode().getCode()==20005){
                return Result.fail(StatusCode.USER_HAS_EXISTED);
            }else{
                return Result.fail(StatusCode.UNKNOWN_ERROR);
            }
        }
    }

    @ApiOperation(value = "通过id删除")
    @GetMapping(value = "deleteById/{id}")
    public Result deleteById(@PathVariable int id){
        try {
            baseUserService.deleteById(id);
            return Result.success("删除成功");
        }catch (AmsException e){
            return Result.fail(StatusCode.USER_NOT_EXIST);
        }
    }

    @ApiOperation(value = "设置权限")
    @PostMapping(value = "setRoles")
    public Result setRoles(UserRoleVM userRoleVM){
        System.out.println(userRoleVM);
        baseUserService.setRoles(userRoleVM.getId(),userRoleVM.getRoles());
        return Result.success("设置成功");
    }

    @ApiOperation(value="将用户信息导入到Excel中",notes="注意！测试的时候请将地址粘贴到浏览器地址栏测试",produces="application/octet-stream")
    @GetMapping(value = "download")
    public void download(HttpServletResponse response) throws Exception{
        // 查询出所有文章信息
        String excelName = "用户信息表记录表";
        String[] headList = new String[]{"编号","身份证","姓名","性别","电话好号码","角色"};
        String[] fieldList = new String[]{"id","idCard","userName","gender","phoneNumber","roles"};
        List<Map<String, Object>> dataList = new ArrayList<>();
        List<BaseUserExtend> list =baseUserService.cascadeRoleFindAll();
        for(BaseUserExtend a : list){
            Map<String, Object> map = new HashMap<>();
            map.put("id",a.getId());
            map.put("idCard",a.getIdCard());
            map.put("userName",a.getUserName());
            map.put("gender",a.getGender());
            map.put("phoneNumber",a.getPhoneNumber());
            map.put("roles", Arrays.toString(a.getRoles().toArray()));
            dataList.add(map);
        }

        //调用工具类导出excel
        ExcelUtils.createExcel(response,excelName,headList,fieldList,dataList);
    }

    @ApiOperation(value="获取本系统统计数据")
    @GetMapping(value = "getStatisticalData")
    public Result getStatisticalData(){
        Statistical statistical = baseUserService.getStatisticalData();
        return Result.success(statistical);
    }

}
